<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm class="pt-[10px]" ref="form" :fieldList="fieldList" :options="formOption" :formData="form">
          <template #ShopCascade>
            <SelectsShopCascade v-model:platform="form.platform_id" v-model:site="form.site" v-model:shop="form.shop_id" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="add" v-hasPermi="[orderStrategyAuthList.scheduling_strategy.add]">
          <span class="dk-iconfont icon-Plus"></span>
          新增
        </VButton>
        <VButton @click="able" v-hasPermi="[orderStrategyAuthList.scheduling_strategy.enable]">
          <span class="dk-iconfont icon-CircleCheck text-[#3487FF]"></span>
           启用
        </VButton>
        <VButton @click="disabled" v-hasPermi="[orderStrategyAuthList.scheduling_strategy.disable]">
          <span class="dk-iconfont icon-Disabled text-[red]"></span>
          禁用
        </VButton>
        <!-- <div class="ml-auto"></div> -->
      </template>
    </VTable>
    <VLog ref="logRef" :api="logApiFn" />
  </VPage>
</template>

<script setup lang="jsx">
import { getBusinessLog, overallOptions, tmsOverallOptions, apiGetLogisticsPreferredStrategy, getWarehouseOptions } from "@/api/public"
import api from "./api"
import { getEnum } from "@/utils/enumUtils"
import { orderStrategyAuthList } from "@/Auth/order-strategy.js"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, onBeforeUpdate, ref, toRefs } from "vue"
import { useRouter } from "vue-router"

import XForm from "@/components/XForm/index.vue"
import VLog from "@/components/VLog"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"

const router = useRouter()

watch(
  () => router.currentRoute.value.path,
  (val, old) => {
    if (["/order-strategy/scheduling-strategy/add", "/order-strategy/scheduling-strategy/update"].includes(old)) {
      query()
    }
  },
  { immediate: true }
)

const data = reactive({
  statusOption: [],
  changeOrderStatus: [],
  shippingRule: [],
  orderPriority: [],
})
const { statusOption, shippingRule, changeOrderStatus, orderPriority } = toRefs(data)
const tableRef = ref()

const datas = reactive({
  shippingMethods: [], // 运输方式
  warehouseOptions: [], // 仓库
  logisticsPreferredStrategy: [], // 物流优选规则
})
const { shippingMethods, warehouseOptions, logisticsPreferredStrategy } = toRefs(datas)

const initOptionList = async () => {
  try {
    // 运输方式
    const resShippingMethod = await tmsOverallOptions({ params: ["mapChannel"] })
    shippingMethods.value = resShippingMethod.data.mapChannel.map((v) => ({ label: v.channel_name, value: v.id }))
    // console.log(shippingMethods.value)
    // 仓库
    const resWarehouse = await getWarehouseOptions({ status: 1 })
    warehouseOptions.value = resWarehouse.data
    // 物流优选规则
    const resLogistics = await apiGetLogisticsPreferredStrategy()
    logisticsPreferredStrategy.value = resLogistics.data
  } catch (error) {
    console.warn(error)
  }
}
const status = [
  { label: "启用", value: 1 },
  { label: "禁用", value: 0 },
]

const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const indicatorTypeOpt = ref([]) //指标
const fieldList = ref([
  {
    slot: "ShopCascade",
  },
  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: status,
    },
    style: { width: "120px" },
  },
  {
    field: "strategy_name",
    placeholder: "策略名称",
    ...publicStyle,
  },

  {
    field: "shipping_method",
    type: "select",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "运输方式",
      data: shippingMethods,
    },
    ...publicStyle,
  },

  {
    field: "shipping_warehouse",
    type: "select",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "发货仓库",
      data: warehouseOptions,
    },
    ...publicStyle,
  },

  {
    field: "dateRange",
    type: "dateTimeRangeNorm",
    style: { width: "380px" },
    select: [{ label: "创建时间", value: "create_time" }],
    selectStyle: { width: "100px" },
  },

  {
    field: "create_user",
    type: "cascader",
    select: [{ label: "创建人", value: "create_user" }],
    style: { width: "280px" },
    selectStyle: { width: "100px" },
  },

  {
    field: "wms_preferred_id",
    type: "select",
    multiple: true,
    collapseTags: true,
    options: {
      placeholder: "物流优选规则",
      data: logisticsPreferredStrategy,
    },
    ...publicStyle,
  },
  {
    field: "product_sku",
    placeholder: "SKU",
    type: "textarea",
    ...publicStyle,
  },
])

// 新增
const add = () => {
  router.push(`/order-strategy/scheduling-strategy/add`)
}
// 删除
const profitSettingDeleteF = (id) => {
  ElMessageBox.confirm(`此操作将永久删除该项，是否继续？`, "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    api.delete(id).then((res) => {
      ElMessage({ message: "删除成功！", type: "success" })
      query()
    })
  })
}
const logRef = ref()
const logApiFn = ref(() => ({}))
const openLog = (id) => {
  logApiFn.value = (dtd) => getBusinessLog({ ...dtd, tag: "order_strategy", business_id: id })
  logRef?.value.open({ id })
  let fields = {
    user: "create_user",
    time: "created_at",
    content: "content",
  }
  logRef?.value.setFields(fields)
}
// 启用
const able = () => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  api.status({ ids: arr, status: 1 }).then((res) => {
    ElMessage({ message: "启用成功！", type: "success" })
    query()
  })
}
// 禁用
const disabled = () => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  api.status({ ids: arr, status: 0 }).then((res) => {
    ElMessage({
      message: "禁用成功！",
      type: "success",
    })
    query()
  })
}
// 查询
const query = () => {
  tableRef?.value.query()
}
//打开详情
// const showDetail = () => {
//   // useRouter/oms/basic-setup/order-source
// }

import { getAloneEnum } from "@/utils/enumUtils"
const originOption = ref({})
// 获取下拉数据
onMounted(async () => {
  overallOptions({ params: ["base.orderStrategy"] }).then((res) => {
    statusOption.value = res.data.baseOrderStrategy.status
    shippingRule.value = res.data.baseOrderStrategy.is_shipping_rule
    orderPriority.value = res.data.baseOrderStrategy.order_priority
  })
  initOptionList()

  let optData = await getAloneEnum(["platform"])
  originOption.value.platform = Object.fromEntries(optData?.platform.map((v) => [v.value, v.label]))
})
getEnum("order_status", (res) => {
  changeOrderStatus.value = res.order_status
})
//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
//获取文本
const getText = (arr, val) => {
  return arr.map((e) => {
    if (e.value == val) {
      return e.label
    }
  })
}
// 列表配置
const tableOptins = reactive({
  rowConfig: { height: 82 },
  formConfig: {
    data: {
      // platform_id: [], // 平台ID
      platform_id: "", // 平台ID
      site: [], // 站点
      shop_id: [], // 店铺ID
      status: 1, // 状态1：启用 0：禁用
      strategy_name: "", // 发货仓库ID
      shipping_method: [], // 运输方式
      shipping_warehouse: [], // 发货仓库ID
      dateRange: { type: "create_time", value: [] }, // 组合+日期范围
      create_user: { type: "create_user", value: [] }, // 创建人ID
      product_sku: [], // 产品sku
      wms_preferred_id: [],
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", params: "left", width: 60 },
    { field: "id", title: "ID", width: 100 },
    { field: "strategy_name", title: "策略名称", width: 250 },
    {
      field: "platform_id_desc",
      title: "平台",
      width: 100,
      slots: {
        default: ({ row }) => <VText value={originOption.value.platform?.[row.platform_id]} />,
      },
    },
    { field: "priority", title: "策略优先级", minWidth: 120 },
    {
      field: "order_priority",
      title: "订单优先级",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return <div>{getText(orderPriority.value, row.order_priority)}</div>
        },
      },
    },
    { field: "exec_order_num", title: "执行订单数量", minWidth: 120 },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={!!row.status} />,
      },
    },

    {
      field: "change_order_status",
      title: "改变订单状态",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return <div>{getText(changeOrderStatus.value, row.change_order_status)}</div>
        },
      },
    },
    {
      field: "commission_rate",
      title: "分配仓库和运输方式",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.is_shipping_rule_desc ? (
                <p>
                  <span class="text-[#666]">类型：</span>
                  {row.is_shipping_rule_desc}
                </p>
              ) : (
                ""
              )}
              <p>
                {!row.is_shipping_rule && row.is_shipping_rule != 0 ? (
                  ""
                ) : row.is_shipping_rule == 0 ? (
                  <div>
                    <p>
                      <span class="text-[#666]">仓库：</span>
                      {row.wms_name}
                    </p>
                    <el-tooltip class="box-item" effect="dark" content={row.shipping_names.join()} placement="top">
                      <p class="ov-text">
                        <span class="text-[#666]">运输方式：</span>
                        {row.shipping_names.join()}
                      </p>
                    </el-tooltip>
                  </div>
                ) : (
                  <div>
                    <p>
                      <span class="text-[#666]">规则名称：</span>
                      {row.rule_name}
                    </p>{" "}
                  </div>
                )}
              </p>
            </div>
          )
        },
      },
    },
    {
      field: "strategy_start_time",
      title: "策略开始时间/策略结束时间",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <p>{row.strategy_start_time}</p>
              <p>{row.strategy_end_time}</p>
            </div>
          )
        },
      },
    },
    {
      field: "creator",
      title: "创建人",
      minWidth: 150,
      slots: {
        default: ({ row }) => <VText value={row.creator} />,
      },
    },
    { field: "create_time", title: "创建时间", width: 170 },
    {
      title: "操作",
      width: 120,
      params: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div class="flex flex-wrap">
              <el-button
                link
                type="primary"
                class="ml-3"
                onClick={() => router.push("/order-strategy/scheduling-strategy/update?id=" + row.id)}
                v-hasPermi={[[orderStrategyAuthList.scheduling_strategy.edit]]}
              >
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => router.push("/order-strategy/scheduling-strategy/add?id=" + row.id)} v-hasPermi={[[orderStrategyAuthList.scheduling_strategy.edit]]}>
                复制
              </el-button>

              <el-button link type="primary" onClick={() => openLog(row.id)} v-hasPermi={[[orderStrategyAuthList.scheduling_strategy.log]]}>
                日志
              </el-button>
              <el-button link type="danger" onClick={() => profitSettingDeleteF(row.id)} v-hasPermi={[[orderStrategyAuthList.scheduling_strategy.delete]]}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...form,
          ...page,
        }
        params.product_sku = params.product_sku?.split("\n").filter((v) => !!v.trim())
        params.product_sku = params.product_sku?.map((v) => v.trim())
        return api.query(params)
      },
    },
  },
})
</script>
<style lang="scss" scoped>
:deep(.ov-text) {
  overflow: hidden !important;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</style>
